package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.RequestUtils;
import com.settlement.system.listener.easyexcel.SysBalanceListener;
import com.settlement.system.model.entity.SysBalance;
import com.settlement.system.model.form.SysBalanceForm;
import com.settlement.system.model.query.SysBalanceQuery;
import com.settlement.system.model.vo.SysBalanceImportVo;
import com.settlement.system.service.SysBalanceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 余额表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-07-29
 */
@RestController
@RequestMapping("/api/v1/balance")
@RequiredArgsConstructor
public class SysBalanceController {

    @Value("${system.config.secret}")
    private String secret;

    @Value("${system.config.appId}")
    private String appId;

    private final SysBalanceService sysBalanceService;

    @GetMapping("/page")
    public PageResult<SysBalance> getPage(@ParameterObject SysBalanceQuery queryParams) {
        Page<SysBalance> result = sysBalanceService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存余额表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:balance:save')")
    public Result<?> saveSysBalance(@RequestBody @Valid SysBalanceForm sysBalanceForm) {
        boolean result = sysBalanceService.saveSysBalance(sysBalanceForm);
        return Result.judge(result);
    }

    @Operation(summary = "RPA保存余额表")
    @PostMapping("/updateBalance")
    public Result<?> updateBalance(HttpServletRequest request, @RequestBody @Valid SysBalanceForm sysBalanceForm) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        boolean success = sysBalanceService.updateBalance(sysBalanceForm);
        return Result.judge(success);
    }

    @Operation(summary = "获取余额表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysBalanceForm> getSysBalanceFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysBalanceForm sysBalance = sysBalanceService.getSysBalanceFormData(id);
        return Result.success(sysBalance);
    }

    @Operation(summary = "删除余额表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:balance:delete')")
    public Result<?> deleteSysBalance(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysBalanceService.deleteSysBalance(ids);
        return Result.judge(result);
    }

    @Operation(summary = "余额表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysBalanceImport")
    @PreAuthorize("@ss.hasPerm('sys:balance:import')")
    @PreventDuplicateSubmit
    public Result<?> sysBalanceImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysBalanceListener listener = new SysBalanceListener();
        EasyExcelFactory.read(file.getInputStream(), SysBalanceImportVo.class, listener).sheet(0).doRead();
        List<SysBalanceImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        sysBalanceService.importData(list);
        return Result.success();
    }

    @Operation(summary = "导出余额表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:balance:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "余额表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<SysBalanceImportVo> sysBalanceList = sysBalanceService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysBalanceImportVo.class).sheet("余额表").doWrite(sysBalanceList);
    }
}

